
export const baseUrl = process.env.NODE_ENV === 'development' ? 'https://gatewaytest.1-1dr.com' :'https://gateway.1-1dr.com';
import util from "./util.js";
import store from '../store/index.js';

const platformCode = "YNS"; //住院陪护请求头

const network = {
  GET: (requestHandler) => {
    return request('GET', requestHandler)
  },
  POST: (requestHandler) => {
    return request('POST', requestHandler)
  },
  DELETE: (requestHandler) => {
    return request('DELETE', requestHandler)
  },
  PUT: (requestHandler) => {
    return request('PUT', requestHandler)
  }
}

const request = (method, requestHandler) => {
  // 注意：可以对params加密等处理
  var params = requestHandler.data;
  var uri = requestHandler.url;
  // var isShowLoading = requestHandler.loading != null ? requestHandler.loading : 0;
  var {
    Authorization,
    userId,
    devAgent
  } = uni.getStorageSync('requestHeader')
  
  return new Promise(function(resolve, reject) {
    // if (isShowLoading == 0) {
    //     wx.showLoading({
    //         title: '加载中',
    //     })
    // }
    uni.request({
      url: baseUrl + uri,
      data: params,
      method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        platformCode, //平台编码
        Authorization, 
        userId,
        companyCode: store.state.companyCode, //机构编码
        devAgent,
        devSystem: 'usermpwx' //设备系统
      }, // 设置请求的 header
      success(res) {
        // 注意：可以对参数解密等处理
        if (res.statusCode == 401 || res.statusCode == 405) {
          uni.showToast({
            title: '请先登录',
            icon: 'none',
            duration: 3000
          })
          setTimeout(() => {
            uni.reLaunch({
              url: `/pages/common/login/login?targetUrl=${encodeURIComponent(util.getCurrentPageUrlWithArgs())}`
            })
          }, 500)
        } else if (res.statusCode == 200 || res.statusCode == 201) {
          resolve(res);
        } else if (res.statusCode == 500 || res.statusCode == 502 || res.statusCode == 501) {
          if (res.data.code == 300) {
            uni.showToast({
              title: res.data.error || res.data.msg,
              icon: 'none',
              duration: 3000
            })
          } else {
            uni.showToast({
              title: '服务器出错',
              icon: 'none',
              duration: 3000
            })
			// uni.showToast({
			//   title: JSON.stringify(params),
			//   icon: 'none',
			//   duration: 30000
			// })
          }
          reject(res.data.code)
        } else {
          uni.showToast({
            title: res.data.error || res.data.msg,
            icon: 'none',
            duration: 3000
          })
          reject(error)
        }
        // setTimeout(function () {
        //     wx.hideLoading()
        // }, 500)
      },
      fail(error) {
        reject(error)
      }
    })
  })
}

export default network;
